const fs = require("fs");
const readline = require("readline");
const { test } = require("./common");
/**
 * 提取中文
 * @param {*} fullPath
 * @returns
 */
const extractCnLang = (fullPath) => {
  const lang = [];
  return new Promise((resolve, reject) => {
    let isNote = false;
    let rl = readline.createInterface({
      input: fs.createReadStream(fullPath),
    });
    let lineIndex = 0;
    rl.on("line", (line) => {
      lineIndex++;
      let content = isNote ? "" : line;
      if (line.includes("/*")) {
        isNote = true;
        content = line.slice(0, line.indexOf("/*"));
      }
      if (line.includes("*/")) {
        if (isNote) {
          isNote = false;
          content = line.slice(line.indexOf("*/") + 2);
        }
      }
      if (line.includes("<!--")) {
        isNote = true;
        content = line.slice(0, line.indexOf("<!--"));
      }
      if (line.includes("-->")) {
        if (isNote) {
          isNote = false;
          content = line.slice(line.indexOf("-->") + 3);
        }
      }
      if (isNote && !content) return;
      if (line.includes("//")) content = line.slice(0, line.indexOf("//"));

      //   if (line.includes("{{")) {
      //     isNote = true;
      //     content = line.slice(0, line.indexOf("}}"));
      //   }

      let str = content.match(test);
      while (str) {
        if (str) {
          str = str[0];
          let otherStr = "";
          if (content.indexOf("'" + str) > -1) {
            let contentArr = content.split(str);
            otherStr = contentArr[1]
              ? contentArr[1].slice(0, contentArr[1].indexOf("'"))
              : "";
          }
          if (content.indexOf('"' + str) > -1) {
            let contentArr = content.split(str);
            otherStr = contentArr[1]
              ? contentArr[1].slice(0, contentArr[1].indexOf('"'))
              : "";
          }

          if (content.indexOf(">" + str) > -1) {
            let contentArr = content.split(str);
            otherStr = contentArr[1]
              ? contentArr[1].slice(0, contentArr[1].indexOf("<"))
              : "";
          }
          if (content.indexOf(str + '"') > -1) {
            let contentArr = content.split(str);
            let reverseStr = contentArr[0].split("").reverse();
            str =
              reverseStr.splice(0, reverseStr.indexOf('"')).reverse().join("") +
              str;
          } else {
            str += otherStr; // .replace(/{{(.*)}}/g, '')
          }
          str = str.trim();
          str = str.replace(/{{(.*)}}$/g, "");

          str && lang.push(str);
        }
        content =
          content.slice(0, content.indexOf(str)) +
          content.slice(content.indexOf(str) + str.length);
        str = content.match(test);
      }
    });
    rl.on("close", () => {
      resolve(lang);
    });
  });
};

module.exports = extractCnLang;
